package com.witframework.components;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.witframework.PropertiesConstants;
import com.witframework.core.ApplicationProperties;
import com.witframework.core.persistence.BaseJdbcDao;
import com.witframework.core.persistence.IBaseJdbcDao;
import com.witframework.web.mvc.Controller;
import com.witframework.web.mvc.WebContext;

@Component
public class CustomSelectController implements Controller{
	

	public String executor(WebContext webContext) {
		String dialogid=webContext.getParameterAndsetAttribute("dialogid");
		String data=webContext.getParameterAndsetAttribute("data");		
		String properties=webContext.getParameterAndsetAttribute("properties");
		String property1=webContext.getParameterAndsetAttribute("property1");
		String otherProperties=resetProperties(properties,property1);
		String property2=webContext.getParameterAndsetAttribute("property2");
		otherProperties=resetProperties(otherProperties,property2);
		String property3=webContext.getParameterAndsetAttribute("property3");
		otherProperties=resetProperties(otherProperties,property3);
		
		String datatype=webContext.getParameterAndsetAttribute("datatype");
		String multiple=webContext.getParameterAndsetAttribute("multiple");
		String selected=webContext.getParameterAndsetAttribute("selected");
		String selectedItems=webContext.getParameterAndsetAttribute("selectedItems");//选择页面的已选择数据（用于保存在翻页时已选择的数据）
		String filterOptions=webContext.getParameterAndsetAttribute("filterOptions");//在数据选择页面自动生成的查询过滤器
		String filters=webContext.getParameterAndsetAttribute("filters");//过条件，目前只用于table类型的数据源	
		String titles=webContext.getParameterAndsetAttribute("titles");
		titles=(String)webContext.getSessionAttribute("customselect_titles"+dialogid);		
		System.out.println(titles);
		try {
			
			data=java.net.URLDecoder.decode(data,"utf-8");
			filters=java.net.URLDecoder.decode(filters,"utf-8");
			//titles=java.net.URLDecoder.decode(titles,"utf-8");			
			
		} catch (Exception e) {			
		}
		if(StringUtils.isNotEmpty(filters)){ 
			filters=StringUtils.replace(filters,"[","'");
			filters=StringUtils.replace(filters,"]","'");
			filters=StringUtils.replace(filters,"eq","=");
			filters=StringUtils.replace(filters,"gt",">");
			filters=StringUtils.replace(filters,"lt","<");
			filters=StringUtils.replace(filters,"ge",">=");
			filters=StringUtils.replace(filters,"le","<=");
			filters=StringUtils.replace(filters,"ne","!=");
			filters=StringUtils.replace(filters,".o/o.","%");	
		}
		List dataList=null;
		List<CustomSelectEcProperty> viewPropertyList=new ArrayList<CustomSelectEcProperty>();
	
		if(datatype.equalsIgnoreCase("table")||datatype.equalsIgnoreCase("sql")){
			IBaseJdbcDao dao=(IBaseJdbcDao)com.witframework.core.BeanFactory.getBean("baseJdbcDao");			
			StringBuffer query=new StringBuffer();
			if(datatype.equalsIgnoreCase("table")){
				query.append("select "+otherProperties+" from "+data);
				for(String property:otherProperties.split(",")){
					query.insert(query.indexOf(property)+property.length()," "+property);
				}
			}else{
				query.append(data);
			}			
			if(StringUtils.isNotEmpty(filters)){ 				
				String dynFilter=BaseJdbcDao.createFilterQuery(webContext.getFilter());
				if(dynFilter!=null)
					filters+=" and "+dynFilter;
			}else{
				filters=BaseJdbcDao.createFilterQuery(webContext.getFilter());
			}			
			
			if(StringUtils.isNotEmpty(filters)){
				if(query.toString().toLowerCase().indexOf(" where ")<0){
					if(query.toString().toLowerCase().indexOf(" order ")<0)
						query.append(" where ").append(filters);
					else
						query.insert(query.toString().toLowerCase().indexOf(" order "), " where "+filters);
				}else{
					query.insert(query.toString().toLowerCase().indexOf(" where ")+7, filters+" and ");
				}
			}
			dataList=dao.pageQuery(webContext.getPageSortModel(dialogid), query.toString());					
			
			
		}else if(datatype.equalsIgnoreCase("class")){
			SelectListDataSource ds;
			try {
				ds = (SelectListDataSource)Class.forName(data).newInstance();
				dataList=ds.getListData(filters);
			} catch (Exception e) {				
				webContext.renderHtml("数据源错误："+datatype);
			}
			
		}else{
			webContext.renderHtml("不支持的数据源类型："+datatype);
		}	
		String [] vps=properties.split(",");
		for(String n:vps){
			String title=n;
			if(titles!=null){
				title=getDisplayFromTitles(n,titles);
			}
			CustomSelectEcProperty ecp=new CustomSelectEcProperty(n,title);
			viewPropertyList.add(ecp);
		}			
		webContext.setAttribute("dataList", dataList);//待选的数据集	
		webContext.setAttribute("viewPropertyList",viewPropertyList);
		if(datatype.equalsIgnoreCase("class"))
				return "classpath:/com/witframework/webroot/framework/common/components/customselectforclass.jsp"+ApplicationProperties.getProperty(PropertiesConstants.WIT);
		else
			return "classpath:/com/witframework/webroot/framework/common/components/customselect.jsp"+ApplicationProperties.getProperty(PropertiesConstants.WIT);
	}	
	private String getDisplayFromTitles(String name, String titles){
		for(String p:titles.split(",")){
			String[] map=p.split(":");
			if(map[0].equalsIgnoreCase(name))
				return map[1];
		}
		return name;
	}
	private String resetProperties(String properties,String other){
		if(StringUtils.isEmpty(properties))			
			return StringUtils.isNotEmpty(other)?other:"";
		String[] ps=properties.split(",");
		for(String p:ps){
			if(p.equals(other))
				return properties;
		}
		return StringUtils.isNotEmpty(other)?(properties+=","+other):properties;
	}
}
